import axios from 'axios'
import routerIndex from '../router/index'
axios.defaults.withCredentials = false
axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded'
axios.defaults.timeout = 5000
//添加一个请求拦截器
axios.interceptors.request.use(function (config) {
  if (config.url.indexOf('login') == -1 && config.url.indexOf('heweather') == -1) {
    let token
    let user = JSON.parse(window.sessionStorage.getItem('userInfo')).page;
    if (user) {
      token = user.token;
    }
    config.headers.common['key'] = token;
  }
  //console.dir(config);
  return config;
}, function (error) {
  // Do something with request error
  console.info("error: ");
  console.info(error);
  return Promise.reject(error);
});

// 添加一个响应拦截器
axios.interceptors.response.use(function (response) {
  if (response.data && response.data.retCode) {
    if (response.data.retCode === 9 || response.data.retCode === 999 ) {
      routerIndex.push('/');
      window.sessionStorage.removeItem('userInfo')
    }
  }
  return response;
}, function (error) {
  // Do something with response error
  console.dir(error);
  return Promise.reject(error);
})

//通用方法
export const POST = (url, params) => {
  const getTimestamp = new Date().getTime();
    return axios.post(`${url}?timer=${getTimestamp}`, params).then(res => res.data)
}
export const GET = (url, params) => {
  const getTimestamp = new Date().getTime();
  return axios.get(`${url}?timer=${getTimestamp}`, {params: params}).then(res => res.data)
}